﻿using System.Diagnostics;
using System.IO;
using System.Linq;
using Microsoft.Office.Interop.Excel;

namespace Haimen.Func2;

internal class MonthResultMaker(
    MonthInputCollector inputCollector,
    ExcelRangeCopier interopCopier) {

  public MonthResultInfo Make(AppEnvPath env) {
    MonthStoreIn[] inputList = _inputCollector.Collect(env);
    Trace.Assert(inputList.Length > 0, "未发现店铺分表文件！");

    string outPath = PrepareOut(env);
    Application excelApp = FillResult(outPath, inputList);

    string month = inputList
      .Select(i => i.Month)
      .Distinct()
      .Single();

    return new(outPath, month, excelApp);
  }

  //t:HmLab.Func2.LbPrepareMonthOut
  string PrepareOut(AppEnvPath path) {
    const string result = "month.xlsx";
    var ResolveTpl = () => {
      string devTpl = path.InDev(result);
      if (File.Exists(devTpl)) {
        System.Console.WriteLine($"检测到dev：{devTpl}");
        return devTpl;
      }

      string resTpl = path.ResFunc2(result);
      Debug.Assert(File.Exists(resTpl));
      return resTpl;
    };

    string outPath = path.OutDir("月合并报表.xlsx");
    string tplPath = ResolveTpl();
    //Console.WriteLine(tplPath);

    File.Copy(tplPath, outPath, overwrite: true);
    return outPath;
  }

  //t:HmLab.Func2.LbFillMonthResult
  Application FillResult(string resultPath, MonthStoreIn[] inputList) {
    Application excelApp = new() {
      Visible = true,
      ScreenUpdating = false,
    };

    Workbooks books = excelApp.Workbooks;
    Workbook toBook = books.Open(resultPath, UpdateLinks: false);

    excelApp.DisplayAlerts = false;
    BookFrom[] copyArg = MakeCopyArg(inputList);
    _interopCopier.Copy(toBook, copyArg);

    excelApp.ScreenUpdating = true;
    toBook.Save();
    toBook.Close();

    return excelApp;
  }

  BookFrom[] MakeCopyArg(MonthStoreIn[] inputList) {
    var MakeBook = (MonthStoreIn input) => {
      CellCopy cellArg = new(FromRange: input.Range, ToCell: "A1");
      SheetTo sheetTo = new(input.ToSheet, From: [new(null, [cellArg])]);
      return new BookFrom(input.Path, [sheetTo]);
    };

    return inputList
      .Select(MakeBook)
      .ToArray();
  }

  readonly MonthInputCollector _inputCollector = inputCollector;
  readonly ExcelRangeCopier _interopCopier = interopCopier;
}

internal record MonthResultInfo(string Path, string Month, Application Excel);
